<script setup>
import { ref,reactive } from 'vue'
import { getCode,useAuthentication,login } from '../../api'
import { UserFilled,Lock} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const imgUrl =   new URL('../../../public/login-head.png',import.meta.url).href
//切换表单 0是登录 1是注册
const formType = ref(0)
//点击切换登录和注册
const handleChange = () => {
        formType.value = formType.value ? 0 : 1
}
//表单数据
const loginForm = reactive({
    userName:'',
    passWord:'',
    validCode:'',
})
//发送验证码
 const countdown = reactive({
    validText: '获取验证码',
    time:60,
  })
  let flag = false
  const countdownChange = () => {
    //如果已发送则不处理
    if(flag) return
    //判断手机号是否正确
    const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
    if(!loginForm.userName || !phoneReg.test(loginForm.userName)){
     return ElMessage({
        message: '请输入正确的手机号',
        type:'warning'
     })
    }
    const time = setInterval(() => {
     if(countdown.time <= 0) {
         countdown.time = 60
         countdown.validText = '获取验证码'
         flag = false
         clearInterval(time)
     } else {
     countdown.time--
     countdown.validText = `剩余${countdown.time}`
     }
    
    },1000)
    flag = true
    //then后面记得传data
    getCode({tel:loginForm.userName}).then(({data}) => {
      console.log(data,'data')
      if(data.code === 10000){
        ElMessage.success('验证码发送成功')
      }
     
    })
  }

  //账号校验规则
  const validateUser = (rule, value, callback) => {
    //不能为空
    if(value === ''){
      callback(new Error('请输入手机号'))
    } else {
      const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
      //是phoneReg在前面  value在括号里面 别再弄反了
      phoneReg.test(value) ? callback() : callback(new Error('手机号格式不正确，请输入正确格式的手机号'))
    }
  }
  //密码校验 
  const validatePass = (rule,value,callback) => {
    if(value === ''){
      callback(new Error('请输入密码'))
    } else {
      const passReg = /^[a-zA-Z0-9_-]{4,16}$/
      passReg.test(value) ? callback() : callback(new Error('密码格式不正确,需要4-16位字母数字下划线'))
    }
  
  }
  //表单校验
  //这个rules 一定要加 在那个 form 属性里面加上  :rules="rules"
  const rules = reactive({
        userName:[{validator: validateUser,trigger: 'blur'}],
        passWord:[{validator: validatePass,trigger: 'blur'}],
  })
    //表单提交
const loginFormRef = ref()

  const submitForm = async (formEl) => {
    await formEl.validate(( valid,fields ) => {
      if(valid){
        console.log(loginForm,'submit')
        //判断是登录还是注册
        if(formType.value){
          useAuthentication(loginForm).then(({data}) => {
            if(data.code === 10000){
              ElMessage.success('注册成功')
              formType.value = 0
            }
          })
        }else{
           login(loginForm).then(({data}) => {
            if(data.code === 10000){
              ElMessage.success('登录成功')
              console.log(data)
              //将token和用户信息缓存到浏览器
              localStorage.setItem('pz-token',data.data.token)
              //userInfo是对象 得通过json.stringify转成字符串
              localStorage.setItem('pz-user',JSON.stringify(data.data.userInfo))
             
               router.push('/')
              
            }
            })
        }
      }else{
       console.log('error',fields)
      }
    
    })
  }
</script>

<template>
    <!-- align那里  而且用的是等号不是冒号前面要加冒号  后面是俩引号 *** -->
<el-row class="login-container" justify="center" :align="'middle'">
    <el-card style="max-width: 480px;">
        <template #header>
            <div class="card-header">
                <!-- ************src前面也要加个冒号 -->
                <img :src="imgUrl" alt="">
            </div>
        </template>
    <div class="jump-link">
        <el-link type="primary" @click="handleChange">{{formType ? '返回登录' : '注册账号'}}</el-link>
    </div>
    <el-form
   
    ref="loginFormRef"  
    :model="loginForm"
    style="max-width: 600px;"
  class="demo-ruleForm"
   
    :rules="rules">
      <el-form-item prop="userName">
        <el-input v-model="loginForm.userName" 
        prefix-icon="UserFilled"
        placeholder="手机号"
        ></el-input>
      </el-form-item>
       <el-form-item  prop="passWord">
        <el-input v-model="loginForm.passWord" 
        type="passWord"
        prefix-icon="Lock"
        placeholder="密码"
        ></el-input>
       </el-form-item>
      <el-form-item v-if="formType" prop="validCode">
          <el-input v-model="loginForm.validCode" 
          placeholder="验证码"
          ><template #append>
            <span @click="countdownChange">{{ countdown.validText }}</span>
          </template>
        </el-input>
           
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width:100%;" 
        @click="submitForm(loginFormRef)"
        >{{formType ? '注册' : '登录'}}</el-button>
      </el-form-item>
    </el-form>
    </el-card>
</el-row>
</template>

<style lang="less" scoped>
:deep(.el-card__header) {
    padding: 0
  }
  .login-container {
    height: 100%;
    .card-header{
      background-color: #899fe1;
      img {
        width: 430px;
      }
    }
    .jump-link {
      text-align: right;
      margin-bottom: 10px;
    }
  }
</style>
